package org.mrjbee.share.it.easy.client.daemon.http;

import java.awt.Desktop;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.mrjbee.share.it.easy.client.daemon.ConfigurationProvider;
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Status;

public class SimpleHttpManager implements HttpManager {
	private String serverUrl;
	private Client client;
	
	/* (non-Javadoc)
	 * @see org.mrjbee.shared.clipboard.client.daemon.http.HttpManager#initClient(org.mrjbee.shared.clipboard.client.daemon.ConfigurationProvider)
	 */
	public void initClient(ConfigurationProvider conf) throws Exception {
		
		serverUrl = conf.getServerBaseUrl();
		
		Context context = new Context();
		client = new Client(context, new Protocol("HTTP"));
		client.start();
		
	}

	/* (non-Javadoc)
	 * @see org.mrjbee.shared.clipboard.client.daemon.http.HttpManager#dropClient()
	 */
	public void dropClient() {
		try {
			client.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see org.mrjbee.shared.clipboard.client.daemon.http.HttpManager#publishString(java.lang.String)
	 */
	public boolean publishString(String string) {
		Request request = new Request(Method.POST, serverUrl+"/data");
		request.setEntity(string, MediaType.TEXT_PLAIN);
		Response response = client.handle(request);
		if (response.getStatus().isSuccess()){
			return true; 
		} else {
			System.out.println("Response Status:"+response.getStatus());
			return false;
		}
	}

	/* (non-Javadoc)
	 * @see org.mrjbee.shared.clipboard.client.daemon.http.HttpManager#grabString()
	 */
	public String grabString() {
		Request request = new Request(Method.GET, serverUrl+"/data");
		Response response = client.handle(request);
		if (response.getStatus().isSuccess()){
			return response.getEntityAsText(); 
		} else {
			System.out.println("Response Status:"+response.getStatus());
			return null;
		}
	}

}
